import { create } from 'zustand';

interface ChartStore {
	chatStatus: boolean;
	newMsgNum: number;
	increaseNewMsgNum: () => void;
	resetNewMsgNum: () => void;
	setChatStatus: (open: boolean) => void;
	initMsgNum: () => void;
}

const newMsgNumKey = 'newMsgNum';

export const useChatStore = create<ChartStore>((set) => ({
	/** 通讯窗口是否打开 */
	chatStatus: false,
	/** 未读消息数量 */
	newMsgNum: 0,

	increaseNewMsgNum: () =>
		set((state) => {
			if (state.chatStatus) return {};
			const newMsgNum = state.newMsgNum + 1;
			localStorage.setItem(newMsgNumKey, JSON.stringify(newMsgNum));
			return { newMsgNum };
		}),
	resetNewMsgNum: () => {
		localStorage.removeItem(newMsgNumKey);
		set({ newMsgNum: 0 });
	},
	setChatStatus: (open) => set({ chatStatus: open }),
	initMsgNum: () => {
		const num = localStorage.getItem(newMsgNumKey) ?? 0;
		set({ newMsgNum: Number(num) });
	}
}));
